# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jhkim

import functools
import logging

from coin.strategy.mm.subscription import get_subscription_key
from coin.exchange.bitflyer_v1.kr_rest.futures_product import BitflyerFuturesProduct
from coin.exchange.bitflyer_v1.kr_rest.product import BitflyerProduct

from coin.base.timestamp import get_timestamp


class SfdCalculator(object):
  def __init__(self):
    self._spot_product = BitflyerProduct.FromStr('BTC-JPY')
    self._fx_product = BitflyerFuturesProduct.FromStr('BTC-JPY.PERPETUAL')
    self._last_spot_price = None
    self._last_fx_price = None

  @property
  def products(self):
    return [self._spot_product, self._fx_product]

  def set_book_reset(self, products, book_builder_name, book_builder):
    for product in [self._spot_product, self._fx_product]:
      subscription_key = get_subscription_key(product)
      if book_builder_name == subscription_key:
        if hasattr(book_builder, "subscribe_trade"):
          book_builder.subscribe_trade(product, functools.partial(self.on_trade, product))

  def on_trade(self, product, trade):
    if product == self._spot_product:
      self._last_spot_price = trade.price
    elif product == self._fx_product:
      self._last_fx_price = trade.price

  def get_sfd(self):
    if self._last_fx_price is None or self._last_spot_price is None:
      return None
    return 100. * self._last_fx_price / self._last_spot_price - 100.

  def is_sfd_unsafe(self):
    sfd = self.get_sfd()
    # if sfd is not None and 4.9 < sfd < 5.1:
    if sfd is not None and sfd < 4.9:
      return False
    logging.info("sfd: %s is unsafe" % sfd)
    return True
